package com.lingyu.jsjx.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingyu.jsjx.domain.TeachingReflection;
import com.lingyu.jsjx.domain.dto.StudentScoreDTO;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanValidators;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteDeptService;
import com.ruoyi.system.api.domain.SysDept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lingyu.jsjx.mapper.StudentScoreMapper;
import com.lingyu.jsjx.domain.StudentScore;
import com.lingyu.jsjx.service.IStudentScoreService;

import javax.validation.Validator;

/**
 * 学生成绩Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-31
 */
@Service
public class StudentScoreServiceImpl extends ServiceImpl<StudentScoreMapper, StudentScore> implements IStudentScoreService {
    @Autowired
    private StudentScoreMapper studentScoreMapper;
    @Autowired
    private RemoteDeptService deptService;
    @Autowired
    private Validator validator;
    /**
     * 查询学生成绩
     *
     * @param scoreId 学生成绩主键
     * @return 学生成绩
     */
    @Override
    public StudentScore selectStudentScoreByScoreId(Long scoreId) {
        return studentScoreMapper.selectStudentScoreByScoreId(scoreId);
    }

    /**
     * 查询学生成绩列表
     * @return 学生成绩
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "sc",type = "jsjx")
    public List<StudentScore> selectStudentScoreList(StudentScoreDTO studentScoreDTO) {
        return studentScoreMapper.selectStudentScoreList(studentScoreDTO);
    }

    /**
     * 新增学生成绩
     *
     * @param studentScore 学生成绩
     * @return 结果
     */
    @Override
    public int insertStudentScore(StudentScore studentScore) {
        return baseMapper.insert(studentScore);
    }

    /**
     * 修改学生成绩
     *
     * @param studentScore 学生成绩
     * @return 结果
     */
    @Override
    public int updateStudentScore(StudentScore studentScore) {
        return baseMapper.updateById(studentScore);
    }

    /**
     * 批量删除学生成绩
     *
     * @param scoreIds 需要删除的学生成绩主键
     * @return 结果
     */
    @Override
    public int deleteStudentScoreByScoreIds(Long[] scoreIds) {
        return studentScoreMapper.deleteStudentScoreByScoreIds(scoreIds);
    }

    /**
     * 删除学生成绩信息
     *
     * @param scoreId 学生成绩主键
     * @return 结果
     */
    @Override
    public int deleteStudentScoreByScoreId(Long scoreId) {
        return baseMapper.deleteById(scoreId);
    }

    @Override
    public List<JSONObject> selectStudentScoreCountByUserId() {
        List<Map<String, Object>> result = studentScoreMapper.selectStudentScoreCountByUserId(SecurityUtils.getUserId());
        return result.stream()
                .map(JSONObject::new)
                .collect(Collectors.toList());
    }

    @Override
    public String importStudentScore(List<StudentScore> studentScoreList, Boolean isUpdateSupport) {
        if (StringUtils.isNull(studentScoreList) || studentScoreList.size() == 0) {
            throw new ServiceException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (StudentScore studentScore : studentScoreList) {
            try {
                SysDept dept1 = deptService.selectDeptByName(studentScore.getCollageName(), 0L, SecurityConstants.INNER).getData();
                SysDept dept2 = null;
                SysDept dept3 = null;

                if (dept1 != null)
                    dept2 = deptService.selectDeptByName(studentScore.getMajorName(), dept1.getDeptId(), SecurityConstants.INNER).getData();
                if (dept2 != null)
                    dept3 = deptService.selectDeptByName(studentScore.getClassName(), dept2.getDeptId(), SecurityConstants.INNER).getData();
                if (dept1 != null) {
                    studentScore.setCollageId(dept1.getDeptId());
                }
                if (dept2 != null) {
                    studentScore.setMajorId(dept2.getDeptId());
                }

                if (dept3 != null) {
                    studentScore.setClassId(dept3.getDeptId());
                }
                studentScore.setTeacherId(SecurityUtils.getUserId());
                studentScore.setTeacherName(SecurityUtils.getUsername());
                studentScore.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
                studentScore.setCreateByName(SecurityUtils.getUsername());
                studentScore.setCreateTime(DateUtils.getNowDate());

                // 验证数据合法性
                BeanValidators.validateWithException(validator, studentScore);
                studentScoreMapper.insert(studentScore);
                successNum++;
                successMsg.append("<br/>" + successNum + "、学情成绩导入成功");
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、学情成绩导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }

        return successMsg.toString();
    }
}
